package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.RefPayInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * RefPayInfoServiceImpl class
 *
 * @author wxr
 * @date 2019/7/1
 */
@Service
public class RefPayInfoServiceImpl implements RefPayInfoService {
    @Autowired
    RefPayInfoMapper refPayInfoMapper;
    @Autowired
    RefReqMapper refReqMapper;
    @Autowired
    RefReqListMapper refReqListMapper;
    @Autowired
    BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    BaseContractorBankInfoMapper baseContractorBankInfoMapper;
    @Autowired
    BaseBankInfoMapper baseBankInfoMapper;
    @Autowired
    SysCoreParamMapper sysCoreParamMapper;
    @Autowired
    AccKeepAccountMapper accKeepAccountMapper;
    @Autowired
    FlowInstanceMapper flowInstanceMapper;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult insert(RefPayInfo refPayInfo) {
        int num = NumberEnum.ZERO.getNum();
        //改申请编号对应的支付编号为废弃
        RefPayInfo ref = refPayInfoMapper.getInfoByReqId(refPayInfo.getReqId());
        if (null != ref && NumStrEnum.TWO.getNum().equals(ref.getAccNoState())) {
            return CommonResult.strResult(num, "已冻结无法生成新凭证！");
        }
        refPayInfoMapper.updateAccNoStateByReqId(refPayInfo.getReqId(), NumStrEnum.THREE.getNum());
        if (null != ref) {
            accKeepAccountMapper.updateState(NumStrEnum.ZERO.getNum(), ref.getPayNo());
        }
        RefReq refReq = refReqMapper.getInfo(refPayInfo.getReqId());
        String value = sysCoreParamMapper.getParamValueByCode(NumStrEnum.TWENTY_TWO.getNum());
        String vaildDate = (null == value || NumStrEnum.ZERO.getNum().equals(value)) ? "2099-12-12" : String.valueOf(LocalDate.now().plusDays(Integer.parseInt(value)));
        refPayInfo.setVaildDate(vaildDate);
        refPayInfo.setPayType(refReq.getRefType());
        refPayInfo.setApproveDate(refReq.getRecDate());
        refPayInfo.setCreater(ShiroUserUtil.getUserName());
        refPayInfo.setReqName(refReq.getReqName());
        String payNo;
        //是否汇总
        //List<RefReqList> list = refReqListMapper.getListByReqId(refPayInfo.getReqId());
        List<RefReqList> list = refReqListMapper.getListByReqIdNoKeep(refPayInfo.getReqId());
        if (NumStrEnum.ONE.getNum().equals(refPayInfo.getCollect())) {
            //汇总取req表数据保存
            payNo = DepositUtil.getNo(NumberEnum.SEVEN.getNum().toString());
            BigDecimal drawBal = BigDecimal.ZERO;
            BigDecimal drawAccr = BigDecimal.ZERO;
            for (RefReqList refReqList : list) {
                drawBal = drawBal.add(refReqList.getPayFundAmount());
                if (null == (refReqList.getPayAccrCal())) {
                    refReqList.setPayAccrCal(BigDecimal.ZERO);
                }
                if (null == (refReqList.getPayAccrAmount())) {
                    refReqList.setPayAccrAmount(BigDecimal.ZERO);
                }
                drawAccr = drawAccr.add(refReqList.getPayAccrAmount().add(refReqList.getPayAccrCal()));
                refReqList.setPayNo(payNo);
                num = refReqListMapper.update(refReqList);
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
            }
            refPayInfo.setPayNo(payNo);
            refPayInfo.setId(UUIDUtil.getUUID());
            refPayInfo.setAmount(refReq.getPayAmount());
            refPayInfo.setDrawBal(drawBal);
            refPayInfo.setDrawAccr(drawAccr);
            //refPayInfo.setDrawAccr(refReqList.getPayAccrAmount());
            num = addAcckeepOne(refPayInfo, payNo, list.get(0).getHouseId(), String.valueOf(list.size()));
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
            num = refPayInfoMapper.insert(refPayInfo);
        } else if (NumStrEnum.ZERO.getNum().equals(refPayInfo.getCollect())) {
            for (RefReqList refReqList : list) {
                payNo = DepositUtil.getNo(NumberEnum.SEVEN.getNum().toString());
                refPayInfo.setPayNo(payNo);
                refPayInfo.setId(UUIDUtil.getUUID());
                refPayInfo.setAmount(refReqList.getPayAmount());
                refPayInfo.setDrawBal(refReqList.getPayFundAmount());
                refPayInfo.setDrawAccr(refReqList.getPayAccrAmount());
                refPayInfo.setAccOwnerName(refPayInfo.getAccOwnerName());
                refPayInfo.setReqListId(refReqList.getId());
                refReqList.setPayNo(payNo);
                num = refReqListMapper.update(refReqList);
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
                num = refPayInfoMapper.insert(refPayInfo);
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
                num = addAcckeepOne(refPayInfo, payNo, refReqList.getHouseId(), NumStrEnum.ONE.getNum());
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
            }
        }
        return CommonResult.ResponseResult(num);
    }

    private int addAcckeep(RefPayInfo refPayInfo, String payNo) {
        //RefReqList refReqList = refReqListMapper.getInfoByreqId(refPayInfo.getReqId());
        //List<RefReqList> list = refReqListMapper.getListByReqId(refPayInfo.getReqId());
        List<RefReqList> list = refReqListMapper.getListByReqIdNoKeep(refPayInfo.getReqId());
        RefReq refReq = refReqMapper.getInfo(refPayInfo.getReqId());
        int num = NumberEnum.ZERO.getNum();
        for (RefReqList refReqList : list) {
            BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(refReqList.getHouseId());
            BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(baseHouseInfo.getBuildNo());
            //添加到表acc_keep
            AccKeepAccount accKeepAccount = new AccKeepAccount();
            accKeepAccount.setBusiNo(payNo);
            accKeepAccount.setBusiType("310");
            accKeepAccount.setCreateTime(DateUtils.getDateNow());
            accKeepAccount.setCreater(ShiroUserUtil.getUserName());
            accKeepAccount.setBankCode(refPayInfo.getContractorBankId());
            accKeepAccount.setPayAmount(refPayInfo.getAmount());
            accKeepAccount.setAccountState(NumStrEnum.ZERO.getNum());
            accKeepAccount.setState(NumStrEnum.ONE.getNum());
            accKeepAccount.setVaildDate(refPayInfo.getVaildDate());
            accKeepAccount.setSpecialAccount(refPayInfo.getSpAccNo());
            accKeepAccount.setReqName(refReq.getReqName());
            accKeepAccount.setSpecialAccount("325");
            accKeepAccount.setRemark(baseHouseInfo.getHouseSite() + "退款");
            accKeepAccount.setRegionId(baseBuildInfo.getRegionNo());
            accKeepAccount.setGrantreqNum(refReq.getReqNo());
            num = accKeepAccountMapper.insert(accKeepAccount);
        }
        return num;
    }

    private int addAcckeepOne(RefPayInfo refPayInfo, String payNo, String houseId, String houseNum) {
        RefReq refReq = refReqMapper.getInfo(refPayInfo.getReqId());
        int num = NumberEnum.ZERO.getNum();

        //List<RefReqList> list = refReqListMapper.getListByReqId(refPayInfo.getReqId());
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(houseId);
        BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(baseHouseInfo.getBuildNo());
        //添加到表acc_keep
        AccKeepAccount accKeepAccount = new AccKeepAccount();
        accKeepAccount.setBusiNo(payNo);
        accKeepAccount.setBusiType("310");
        accKeepAccount.setCreateTime(DateUtils.getDateNow());
        accKeepAccount.setCreater(ShiroUserUtil.getUserName());
        accKeepAccount.setBankCode(refPayInfo.getContractorBankId());
        accKeepAccount.setPayAmount(refReq.getPayAmount());
        accKeepAccount.setAccountState(NumStrEnum.ZERO.getNum());
        accKeepAccount.setState(NumStrEnum.ONE.getNum());
        accKeepAccount.setVaildDate(refPayInfo.getVaildDate());
        accKeepAccount.setSpecialAccount(refPayInfo.getSpAccNo());
        accKeepAccount.setReqName(refReq.getReqName());
        accKeepAccount.setGrantreqNum(refReq.getReqNo());
        accKeepAccount.setSpecialAccount("325");
        accKeepAccount.setGrantreqNum(refReq.getReqNo());
        if (NumStrEnum.ZERO.getNum().equals(refPayInfo.getCollect())) {
            accKeepAccount.setRemark(baseHouseInfo.getHouseSite() + "退款");
        } else if (NumStrEnum.ONE.getNum().equals(refPayInfo.getCollect())) {
            accKeepAccount.setRemark(baseBuildInfo.getBuildName() + "(" + houseNum + ")退款");
        }
        accKeepAccount.setRegionId(baseBuildInfo.getRegionNo());
        num = accKeepAccountMapper.insert(accKeepAccount);
        return num;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult addNewVoucher(String id) {
        int num = NumberEnum.ZERO.getNum();
        RefPayInfo info = refPayInfoMapper.getInfo(id);
        if (null != info && NumStrEnum.TWO.getNum().equals(info.getAccNoState())) {
            return CommonResult.strResult(num, "已冻结无法生成新凭证！");
        }
        if (null != info && NumStrEnum.FOUR.getNum().equals(info.getAccNoState())) {
            return CommonResult.strResult(num, "已记账无法生成新凭证！");
        }
        List<RefReqList> listByPayNo = refReqListMapper.getListByPayNo(info.getPayNo());
        if (null != info && NumStrEnum.ONE.getNum().equals(info.getCollect())) {
            return CommonResult.strResult(num, "汇总状态不可生成新凭证！请重新添加！");
        }
        String oldPayNo = info.getPayNo();
        String payNo = DepositUtil.getNo(NumberEnum.SEVEN.getNum().toString());
        info.setId(UUIDUtil.getUUID());
        info.setPayNo(payNo);
        String value = sysCoreParamMapper.getParamValueByCode(NumStrEnum.TWENTY_TWO.getNum());
        String vaildDate = (null == value || NumStrEnum.ZERO.getNum().equals(value)) ? "2099-12-12" : String.valueOf(LocalDate.now().plusDays(Integer.parseInt(value)));
        info.setVaildDate(vaildDate);
        info.setCreater(ShiroUserUtil.getUserName());
        refPayInfoMapper.updateAccNoStateById(NumStrEnum.THREE.getNum(), id);
        num = refPayInfoMapper.insert(info);
        //修改reqlist凭证编号
        if (num > 0) {
            refReqListMapper.updatePayNoByOldPayNo(payNo, oldPayNo);
        }
        accKeepAccountMapper.updateState(NumStrEnum.ZERO.getNum(), oldPayNo);
        //TODO
        //addAcckeepOne(info,payNo);
        num = addAcckeepOne(info, payNo, listByPayNo.get(0).getHouseId(), NumStrEnum.ONE.getNum());
        return CommonResult.ResponseResult(num);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult addNewCollectVoucher(String id) {
        int num = NumberEnum.ZERO.getNum();
        RefPayInfo info = refPayInfoMapper.getInfo(id);
        List<RefReqList> listByPayNo = refReqListMapper.getListByPayNo(info.getPayNo());
        String oldPayNo = info.getPayNo();
        if (null != info && NumStrEnum.TWO.getNum().equals(info.getAccNoState())) {
            return CommonResult.strResult(num, "已冻结无法生成新凭证！");
        }
        if (null != info && NumStrEnum.FOUR.getNum().equals(info.getAccNoState())) {
            return CommonResult.strResult(num, "已记账无法生成新凭证！");
        }
        if (null != info && NumStrEnum.ZERO.getNum().equals(info.getCollect())) {
            return CommonResult.strResult(num, "非汇总状态不可生成新凭证！请重新添加！");
        }
        String payNo = DepositUtil.getNo(NumberEnum.SEVEN.getNum().toString());
        info.setId(UUIDUtil.getUUID());
        info.setPayNo(payNo);
        String value = sysCoreParamMapper.getParamValueByCode(NumStrEnum.TWENTY_TWO.getNum());
        String vaildDate = (null == value || NumStrEnum.ZERO.getNum().equals(value)) ? "2099-12-12" : String.valueOf(LocalDate.now().plusDays(Integer.parseInt(value)));
        info.setVaildDate(vaildDate);
        info.setCreater(ShiroUserUtil.getUserName());
        refPayInfoMapper.updateAccNoStateById(NumStrEnum.THREE.getNum(), id);
        num = refPayInfoMapper.insert(info);
        //修改reqlist凭证编号
        if (num > 0) {
            /*List<RefReqList> listByReqIdNoKeep = refReqListMapper.getListByReqIdNoKeep(id);
            for (RefReqList r: listByReqIdNoKeep){
                refReqListMapper.updatePayNoByOldPayNo(payNo,oldPayNo);
            }*/
            refReqListMapper.updatePayNoByOldPayNo(payNo, oldPayNo);
        }
        accKeepAccountMapper.updateState(NumStrEnum.ZERO.getNum(), oldPayNo);
        addAcckeepOne(info, payNo, listByPayNo.get(0).getHouseId(), String.valueOf(listByPayNo.size()));
        return CommonResult.ResponseResult(num);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult collectVoucher(String reqId) {
//        int count = refPayInfoMapper.getDjCountByReqId(reqId);
//        if (count > 0) {
//            return CommonResult.strResult(0, "有冻结凭证或记账数据无法汇总！");
//        }
        List<RefReqList> refReqLists = refReqListMapper.getListByReqId(reqId);
        List<RefPayInfo> refPayInfos = refPayInfoMapper.selectAllPayNo(reqId, "1,5");
        if (refPayInfos.size() != refReqLists.size()) {
            List<RefPayInfo> ref = refPayInfoMapper.getListByReqIdNot(reqId);
            if (ref.size() > 0) {
                return CommonResult.ResponseResult(0, "编号为" + ref.get(0).getPayNo() + "已" + ref.get(0).getAccNoState() + "无法汇总");
            } else {
                List<RefReqList> refreq = refReqListMapper.refDel(reqId);
                return CommonResult.ResponseResult(0, refreq.get(0).getHouseSite() + "已被撤销无法汇总");
            }


        }

        List<RefPayInfo> listByReqId = refPayInfoMapper.getListByReqId(reqId);
        //keep表的记录改为废弃
        for (RefPayInfo r : listByReqId) {
            accKeepAccountMapper.updateState(NumStrEnum.ZERO.getNum(), r.getPayNo());
        }
        //根据id查询当前内容
        RefPayInfo info = refPayInfoMapper.getInfoByReqId(reqId);
        List<RefReqList> listByPayNo = refReqListMapper.getListByPayNo(info.getPayNo());
        String oldPayNo = info.getPayNo();
        //改申请编号对应的支付编号为废弃
        RefReq refReq = refReqMapper.getInfo(reqId);
        String value = sysCoreParamMapper.getParamValueByCode(NumStrEnum.TWENTY_TWO.getNum());
        String vaildDate = (null == value || NumStrEnum.ZERO.getNum().equals(value)) ? "2099-12-12" : String.valueOf(LocalDate.now().plusDays(Integer.parseInt(value)));
        RefPayInfo refPayInfo = new RefPayInfo();
        refPayInfo.setVaildDate(vaildDate);
        refPayInfo.setPayType(refReq.getRefType());
        refPayInfo.setApproveDate(refReq.getRecDate());
        refPayInfo.setCreater(ShiroUserUtil.getUserName());
        refPayInfo.setReqName(refReq.getReqName());
        refPayInfo.setCollect(NumStrEnum.ONE.getNum());
        String payNo = DepositUtil.getNo(NumberEnum.SEVEN.getNum().toString());
        refPayInfo.setPayNo(payNo);
        refPayInfo.setId(UUIDUtil.getUUID());
        //refPayInfo.setAmount(refReq.getPayAmount());
        refPayInfo.setReqId(reqId);
        refPayInfo.setBankId(info.getBankId());
        refPayInfo.setSpAccNo(info.getSpAccNo());
        refPayInfo.setContractorBankId(info.getContractorBankId());
        refPayInfo.setPhone(info.getPhone());
        RefReqList amount = refReqListMapper.getPayAmountByReqIdToVoucher(reqId);
        refPayInfoMapper.updateAccNoStateByReqId(reqId, NumStrEnum.THREE.getNum());
        refPayInfo.setAmount(amount.getPayAmount());
        refPayInfo.setDrawAccr(amount.getPayAccrAmount());
        refPayInfo.setDrawBal(amount.getPayFundAmount());
        int num = refPayInfoMapper.insert(refPayInfo);
        //修改reqlist payno
        if (num > 0) {
            //refReqListMapper.updatePayNoByReqId(payNo,reqId);
            List<RefReqList> listByReqIdNoKeep = refReqListMapper.getListByReqIdNoKeep(reqId);
            for (RefReqList r : listByReqIdNoKeep) {
                refReqListMapper.updatePayNoByOldPayNo(payNo, r.getPayNo());
            }
            //新增keep
            addAcckeepOne(info, payNo, listByPayNo.get(0).getHouseId(), String.valueOf(listByPayNo.size()));
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    public RefPayInfo selectReqPayInfo(String reqNo) {
        RefPayInfo refPayInfo = refPayInfoMapper.selectReqPayInfo(reqNo);
        if (null == refPayInfo) {
            return null;
        }
        refPayInfo.setHfmpDate(DateUtils.getDateNow());
        refPayInfo.setCertDate(DateUtils.getDateNow());
        return refPayInfo;
    }

    @Override
    public PageInfo<RefPayInfo> selectReqPayInfoList(Page page, RefPayInfo refPayInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<RefPayInfo> list = refPayInfoMapper.selectReqPayInfoList(refPayInfo);
        PageInfo<RefPayInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public CommonResult updateaccNoState(String id, String accNoState, String state, String certDate) {
        refPayInfoMapper.updateaccNoState(id, accNoState, state, certDate);
        AccKeepAccount keepAccount = new AccKeepAccount();
        keepAccount.setId(id);
        accKeepAccountMapper.update(keepAccount);
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    @Override
    public PageInfo<RefPayInfo> selectRegionName(Page page, RefPayInfo refPayInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<RefPayInfo> list = refPayInfoMapper.selectRegionName(refPayInfo);
        PageInfo<RefPayInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<RefPayInfo> selectPayNo() {
        return refPayInfoMapper.selectPayNo();
    }

    @Override
    public PageInfo<RefPayInfo> getBatchRefundPrintList(Page page, String id) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<RefPayInfo> list = refPayInfoMapper.getBatchRefundPrintList(id);
        //查询清册头信息
        RefPayInfo printHead = refPayInfoMapper.getBatchRefundPrintHead(id);
        if (list.size() > 0) {
            //赋值头信息给第一条
            list.get(0).setPayNo(printHead.getPayNo());
            list.get(0).setHouseCount(printHead.getHouseCount());
            list.get(0).setTotalAmount(printHead.getTotalAmount());
            RefPayInfo total = refPayInfoMapper.getBatchRefundPrintTotal(id);
            setList(list, total);
        }
        PageInfo<RefPayInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public RefPayInfo getNoCollectPrintVoucher(String id) {
        return refPayInfoMapper.getNoCollectPrintVoucher(id);
    }

    @Override
    public RefPayInfo getCollectPrintVoucher(String id) {
        return refPayInfoMapper.getCollectPrintVoucher(id);
    }

    @Override
    public RefPayInfo selectPayInfoByNo(String payNo) {
        if (StringUtils.isBlank(payNo)) {
            return new RefPayInfo();
        }
        return refPayInfoMapper.getInfoByPayNo(payNo);
    }

    /**
     * 给list赋值本页合计  总合计
     *
     * @param list
     * @param total
     */
    private void setList(List<RefPayInfo> list, RefPayInfo total) {
        list.add(setPageTotalList(list));
        list.add(total);
    }

    /**
     * 计算本页合计
     *
     * @param list
     * @return
     */
    private RefPayInfo setPageTotalList(List<RefPayInfo> list) {
        //本页总计
        RefPayInfo pageTotal = new RefPayInfo();
        BigDecimal payFundAmount = BigDecimal.ZERO;
        BigDecimal payAccrAmount = BigDecimal.ZERO;
        BigDecimal payAmount = BigDecimal.ZERO;
        BigDecimal firstDue = BigDecimal.ZERO;
        BigDecimal fundBal = BigDecimal.ZERO;
        for (RefPayInfo refPayInfo : list) {
            payFundAmount = payFundAmount.add(refPayInfo.getPayFundAmount());
            payAccrAmount = payAccrAmount.add(refPayInfo.getPayAccrAmount());
            payAmount = payAmount.add(refPayInfo.getPayAmount());
            firstDue = firstDue.add(refPayInfo.getFirstDue());
            fundBal = fundBal.add(refPayInfo.getFundBal());
        }
        pageTotal.setPayFundAmount(payFundAmount);
        pageTotal.setPayAccrAmount(payAccrAmount);
        pageTotal.setPayAmount(payAmount);
        pageTotal.setFirstDue(firstDue);
        pageTotal.setFundBal(fundBal);
        return pageTotal;
    }

    @Override
    public CommonResult update(RefPayInfo refPayInfo) {
        RefPayInfo info = refPayInfoMapper.getInfo(refPayInfo.getId());
        int num = NumberEnum.ZERO.getNum();
        LocalDate getHfmpDate = LocalDate.parse(refPayInfo.getHfmpDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate getVaildDate = LocalDate.parse(info.getVaildDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (getHfmpDate.isAfter(getVaildDate)) {
            return CommonResult.ResponseResult(num, "超过缴存时间");
        }
        num = refPayInfoMapper.update(refPayInfo);
        return CommonResult.ResponseResult(num);
    }

    @Override
    public CommonResult delete(String id) {
        return null;
    }

    @Override
    public PageInfo<RefPayInfo> getList(Page page, RefPayInfo refPayInfo) {
        return null;
    }

    @Override
    public RefPayInfo getInfo(String id) {
        return null;
    }

    @Override
    public RefPayInfo getPayList(String reqId, String accNoState, String fuzzy) {
        List<RefPayInfo> refPayInfos = refPayInfoMapper.getPayList(reqId, accNoState, fuzzy);
        if (refPayInfos.isEmpty()) {
            return null;
        }
        RefPayInfo refPayInfo = refPayInfos.get(0);
        BaseBankInfo base = baseContractorBankInfoMapper.selectBankNameById(refPayInfo.getContractorBankId());
        refPayInfo.setAccName(refPayInfo.getBankId());
        refPayInfo.setSpAccName(base.getBankName());
        refPayInfo.setAccNo(refPayInfo.getSpAccNo());
        refPayInfo.setSpAccNo(base.getBankAcc());
        String date = flowInstanceMapper.recDate(reqId);
        if (StringUtils.isNotBlank(date)) {
            refPayInfo.setRecDate(date.substring(0, 10));
        }
        return refPayInfo;
    }

    /**
     * 有效日期
     *
     * @param id
     * @param vaildDate
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult changeDate(String vaildDate, String id) {
        int num;
        num = refPayInfoMapper.changeDate(vaildDate, id);
        if (num == 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        num = accKeepAccountMapper.updateVaildDateByNo(id, vaildDate);
        return CommonResult.ResponseResult(num);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public synchronized CommonResult insertOrupdate(RefPayInfo refPayInfo) {
        int no;
        int num = NumberEnum.ZERO.getNum();
        if (refPayInfo.getReqType().equals(NumStrEnum.ZERO.getNum())) {
            //若之前有业务则先更改状态
            no = refPayInfoMapper.selectAccNoStateByReqid(refPayInfo.getReqId(), "1,5");
            if (no != 0) {
                //查询出原有业务的支付编号并把状态修改为0
                AccKeepAccount accKeepAccount = accKeepAccountMapper.selectCountByReqId(refPayInfo.getReqId());
                if (null != accKeepAccount) {
                    accKeepAccount.setState(NumStrEnum.ZERO.getNum());
                    num = accKeepAccountMapper.update(accKeepAccount);
                    if (num == NumberEnum.ZERO.getNum()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }
                }
                num = refPayInfoMapper.updateAccNoStateByReqid(NumStrEnum.THREE.getNum(), refPayInfo.getReqId());
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
            }
            //若冻结
            no = refPayInfoMapper.selectAccNoStateByReqid(refPayInfo.getReqId(), NumStrEnum.TWO.getNum());
            if (no != 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "有冻结的业务请先解冻在新增");
            }
        }
        String uuid = UUIDUtil.getUUID();
        refPayInfo.setId(uuid);
        RefReqList refReqList = refReqListMapper.getInfoByreqId(refPayInfo.getReqId());
        RefReq refReq = refReqMapper.getInfo(refPayInfo.getReqId());
        //baseContractorBankInfoMapper
        BigDecimal bigDecimal = BigDecimal.ZERO;
        if (null != refReqList.getPayFundAmount()) {
            refPayInfo.setDrawBal(refReqList.getPayFundAmount());
        }
        if (null != refReqList.getPayAccrAmount()) {
            if (null != refReqList.getPayAccrCal()) {
                refPayInfo.setDrawAccr(refReqList.getPayAccrAmount().add(refReqList.getPayAccrCal()));
            } else {
                refPayInfo.setDrawAccr(refReqList.getPayAccrCal());
            }
        } else {
            refPayInfo.setDrawAccr(bigDecimal);
        }
        refPayInfo.setPayType(refReq.getRefType());
        refPayInfo.setState(NumStrEnum.FOUR.getNum());
        refPayInfo.setBankId(refPayInfo.getBankId());
        refPayInfo.setSpAccNo(refPayInfo.getAccNo());
        refPayInfo.setSpAccName(refPayInfo.getAccName());
        refPayInfo.setAmount(refReq.getPayAmount());
        refPayInfo.setAccNoState(NumStrEnum.ONE.getNum());
        refPayInfo.setReqListId(refReqList.getId());
        refPayInfo.setCollect(NumStrEnum.ZERO.getNum());
        String payNo = DepositUtil.getNo("7");
        refPayInfo.setPayNo(payNo);
        refPayInfo.setPhone(refPayInfo.getPhone());
        if (StringUtils.isBlank(refPayInfo.getPrintDate())) {
            refPayInfo.setPrintDate(null);
        }
        refReqList.setPayNo(payNo);
        String day = sysCoreParamMapper.selectOne("退款凭证有效天数");
        LocalDate beginDateTime = LocalDate.parse(DateUtils.getDateNow(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (StringUtils.isNotBlank(day) || day.equals(NumStrEnum.ZERO.getNum())) {
            long l = Long.parseLong(day);
            beginDateTime = beginDateTime.plusDays(l);
            refPayInfo.setVaildDate(beginDateTime.toString());
        }
        num = refReqListMapper.update(refReqList);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //添加到表acc_keep
        num = addAcckeep(refPayInfo, payNo);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        refReqMapper.update(refReq);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        String value = sysCoreParamMapper.getParamValueByCode(NumStrEnum.TWENTY_TWO.getNum());
        String vaildDate = (null == value || NumStrEnum.ZERO.getNum().equals(value)) ? "2099-12-12" : String.valueOf(LocalDate.now().plusDays(Integer.parseInt(value)));
        refPayInfo.setVaildDate(vaildDate);
        num = refPayInfoMapper.insert(refPayInfo);
        return CommonResult.ResponseResult(num);
    }

    @Override
    public PageInfo<RefPayInfo> selectPayMessage(Page page, RefPayInfo refPayInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<RefPayInfo> list = new ArrayList<>();
        if (StringUtils.isBlank(refPayInfo.getFuzzy())) {
            list = refPayInfoMapper.selectPayMessage(refPayInfo);
        } else {
            list = refPayInfoMapper.selectPayMessageFuzzy(refPayInfo.getId(), refPayInfo.getFuzzy());
        }
        PageInfo<RefPayInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult updateAccNoStateById(String id, String accNoState) {
        RefPayInfo refPayInfo = refPayInfoMapper.getInfo(id);
        //撤销看是否为多条数据，若为多条则无法撤销
        if (refPayInfo.getCollect().equals(NumStrEnum.ZERO.getNum())) {
            if ((NumStrEnum.ZERO.getNum()).equals(accNoState)) {
                int re = refPayInfoMapper.selectByReqIdState(refPayInfo.getReqId());
                if (re > 1) {
                    return CommonResult.ResponseResult(0, "请汇总打印之后撤销");
                }
            }
        }
        if (refPayInfo.getAccNoState().equals(NumStrEnum.FOUR.getNum())) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "已记账无法撤销");
        }
        int num = refPayInfoMapper.updateAccNoStateById(accNoState, id);
        if (num > 0) {
            int no = accKeepAccountMapper.selectCountByNo(refPayInfo.getPayNo());
            if (no > 0) {
                if ((NumStrEnum.ONE.getNum()).equals(accNoState)) {
                    num = accKeepAccountMapper.updateState(NumStrEnum.ONE.getNum(), refPayInfo.getPayNo());
                    if (num == NumberEnum.ZERO.getNum()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }
                } else if ((NumStrEnum.ZERO.getNum()).equals(accNoState)) {
                    num = accKeepAccountMapper.updateState(NumStrEnum.ZERO.getNum(), refPayInfo.getPayNo());
                    if (num == NumberEnum.ZERO.getNum()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }
                } else if ((NumStrEnum.TWO.getNum()).equals(accNoState)) {
                    num = accKeepAccountMapper.updateState(NumStrEnum.ZERO.getNum(), refPayInfo.getPayNo());
                    if (num == NumberEnum.ZERO.getNum()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                    }
                }
            }
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    public List<RefPayInfo> getPayListToBatchRefByReqId(String reqId, String fuzzy) {
        List<RefPayInfo> payPayInfoList = refPayInfoMapper.getPayListToBatchRefByReqId(reqId, fuzzy);
        payPayInfoList.forEach(refPayInfo ->
                refPayInfo.setIsPrint((null != refPayInfo.getPrintNum() && Integer.parseInt(refPayInfo.getPrintNum()) > 0) ? "是" : "否")
        );
        return payPayInfoList;
    }
}
